package com.will.nio.selector;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

import static com.will.nio.buffer.ByteBufferUtil.debugRead;

/**
 * @author Will
 * @description:
 *              服务器端    -   阻塞
 *              使用 NIO 来理解阻塞模式，单线程
 * @date 2023-04-12 19:21
 * @version: 1.0
 */
@Slf4j
public class BlockingServer {
    public static void main(String[] args) throws IOException {
        // 0. ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1. 创建服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 2. 绑定监听端口
        ssc.bind(new InetSocketAddress(8080));
        // 3. 连接集合
        ArrayList<SocketChannel> channels = new ArrayList<>();
        while (true) {
            log.debug("connecting...");
            // 4. accept 与客户端建立连接，SocketChannel 用来与客户端之间通信
            SocketChannel sc = ssc.accept(); // 阻塞方法，线程停止运行
            log.debug("connected...");
            channels.add(sc);
            for (SocketChannel channel : channels) {
                // 5. 接收客户端发送的数据
                log.debug("before read... {}", channel);
                channel.read(buffer); // 阻塞方法，线程停止运行
                buffer.flip();
                debugRead(buffer);
                buffer.clear();
                log.debug("after read... {}", channel);
            }
        }
    }
}
